import { STORAGE_KEY } from './storage'
var eventUrl = "https://wx.17u.cn/wireless/monitor/wx/common/event",
  pageUrl = "https://wx.17u.cn/wireless/monitor/wx/common/pageview",
  app = {
    "appId": 36,
    "appVersion": "4.0.5",
    "versionTime": "2020.10.22"
  },
  // savior = require("../page/techcenter/common/util/savior.js"),
  config = {
    pagename: "", //一个完整视图的名称
    orgpagename: "", //当前页面的上级页面名称
    resourceid: "", //详情页资源id
    platcode: "", //平台码
    productcode: "", //产品码
    category: "",
    action: "",
    label: "",
    value: "",
    serialid: "",
    prepayid: '',
    unionid: '',
    memberid: '',
    innerRefid: '',
    expandfield: '',
    rpagename: '',//根页面名称
    pagestate: '',//页面状态
    pagedetail: '',//页面浏览详情
    eventid: 0,//事件id
    stayTime: 0,
    immediately: false,//是否立即上报
    getData: '',//获取上报参数回调
  },
  // elconfig = {
  //   et: '',//事件类型
  //   pt: '',//页面名称
  //   cspot: '',//点击位名称，仅et为click事件才赋值
  //   tri: '',//info名称，用来区分不同的info事件，通常指定为触发info事件的click或show
  //   etinf: '',//自定义扩展字段，json格式
  //   if: '',//标识专题与活动
  //   of: '',//标识唤起APP的访问来源，或者跳转到H5的外部来源
  //   ch: '',//频道入口标识，由首页点击位赋值

  //   pturl: '',//页面url show事件需要记录
  // },
  // elSelfData = {
  //   bns: 3,//代码类型，区分H5、APP与pc的标识，小程序为3
  //   ct: 5,//容器（端），可以和bns使用区分小程序内嵌h5， 小程序5
  //   cid: '',//区分用户的唯一标识，openid
  //   orderfrom: 60001,//订单来源，继承老的业绩统计orderfrom字段
  //   snum: '',//unionid
  //   pid: '',//openid
  //   ecrd: '',//会员卡号
  //   dt: '',//1—Iphone，2—Ipad，3—Android，5—Winphone,7—PC，8—androidpad，9—windowspad，99—Unkown 设备类型
  //   chid: 'wxqbh5',//channelid 或者ref的值
  //   lat: '',//当前用户定位 纬度
  //   lng: '',//当前用户定位 经度
  //   cty: '北京',//用户所在城市
  //   ca: '',//浏览器UserAgent
  //   mvt: 'test',//实验分组信息
  //   st: '',//日志记录时间 时间戳，客户端时间，会校准
  //   hoff: '',//场景值
  //   net: '',//网络类型
  //   wxrefid: '',
  // },
  selfData = {
    openid: "", //用户身份唯一标识
    userid: "",
    platcode: "10015",
    country: "", //国家
    province: "", //省份
    city: "", //城市
    county: "", //区县
    sessionid: "", //会话ID
    pagecount: "", //页面PV
    sessioncount: "", //页面UV
    appId: app.appId || "",
    appVersion: app.appVersion || "",
    unionid: '',
  },
  baseInfo = {
    appid: app.appId || "",
    appv: app.appVersion || "",
    plc: '10015',

  };

function isObject(obj) {
  return ({}).toString.call(obj) === "[object Object]";
}

function setLocation() {
  let commonLocationCache = wx.getStorageSync('commonLocationCache')
  if (commonLocationCache && commonLocationCache.data) {
    let data = commonLocationCache.data || {};
    let detail = data.detail || {}
    let ad_info = detail.ad_info || {}
    if (ad_info.nation_code != 156) {//国外
      let address_component = detail.address_component || {}
      selfData.country = address_component.nation;
      selfData.province = address_component.ad_level_1;
      selfData.city = address_component.locality;
      selfData.county = address_component.ad_level_2 || '';
    } else {//国内
      selfData.country = ad_info.nation;
      selfData.province = ad_info.province;
      selfData.city = ad_info.city;
      selfData.county = ad_info.district || '';
    }
  }
}

// 设置网络类型
function setConnection() {

  if (selfData.Connection) return;
  wx.getNetworkType({
    success: function (res) {
      // 返回网络类型, 有效值：
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      selfData.Connection = res.networkType
    }
  })
}
wx.onNetworkStatusChange && wx.onNetworkStatusChange(function (res) {
  selfData.Connection = res.networkType
})
setConnection()
var sessionId = 0;
function setSessionId(type) {//type=1是重新生成sessionid
  sessionId = wx.getStorageSync(STORAGE_KEY.sessionId);
  var now = +new Date();
  if (type == 1 || !sessionId || now - sessionId > 1800000) {
    sessionId = +new Date()
    wx.setStorageSync(STORAGE_KEY.sessionId, sessionId)
    resetPagePv(); //清除后重新计数
    setPageUv(); //UV开始计算
  }
}

function getSessionId() {
  sessionId = sessionId || wx.getStorageSync(STORAGE_KEY.sessionId);
  return sessionId;
}
var _tc_page_pv = ''
function resetPagePv() {
  try {
    _tc_page_pv = ''
  } catch (e) { }
}
//页面访问次数
function setPagePv() {
  if (_tc_page_pv) {
    ++_tc_page_pv
  } else {
    _tc_page_pv = 1
  }
}
var _tc_page_uv = 0;
function getPageUv() {
  _tc_page_uv = _tc_page_uv || wx.getStorageSync(STORAGE_KEY.tcPageUV)
  return _tc_page_uv;
}

function getPagePv() {
  return _tc_page_pv;
}


function setPageUv() {
  var pageUv = _tc_page_uv || wx.getStorageSync(STORAGE_KEY.tcPageUV);
  if (pageUv) {
    _tc_page_uv = ++pageUv
    wx.setStorageSync(STORAGE_KEY.tcPageUV, _tc_page_uv)
  } else {
    _tc_page_uv = 1;
    wx.setStorageSync(STORAGE_KEY.tcPageUV, 1)
  }
}

function eventParamsCheck(oEvent) {
  if (oEvent.settings.debug) {

    if (!selfData.appId) {
      throw new Error("appId不能为空！");
    }

    if (!oEvent.settings.pagename) {
      throw new Error("pagename不能为空！");
    }

    if (!selfData.platcode) {
      throw new Error("platcode不能为空！");
    }

    if (!oEvent.settings.productcode) {
      throw new Error("productcod不能为空！");
    }

    if (!oEvent.settings.category) {
      throw new Error("category不能为空！");
    }

    if (!oEvent.settings.action) {
      throw new Error("action不能为空！");
    }

    if (!oEvent.settings.label) {
      throw new Error("label不能为空！");
    }

    if (!oEvent.settings.value) {
      throw new Error("value不能为空！");
    }

    return true;
  } else {
    return !!oEvent.settings.pagename &&
      !!oEvent.settings.productcode &&
      !!oEvent.settings.category &&
      !!oEvent.settings.action &&
      !!oEvent.settings.label &&
      !!oEvent.settings.value
  }
}

function pageParamsCheck(page) {
  if (page.settings.debug) {

    if (!selfData.appId) {
      throw new Error("appId不能为空！");
    }

    if (!page.settings.pagename) {
      throw new Error("pagename不能为空！");
    }

    if (!selfData.platcode) {
      throw new Error("platcode不能为空！");
    }

    if (!page.settings.productcode) {
      throw new Error("productcode不能为空！");
    }

    if (!getSessionId()) {
      throw new Error("sessionId不能为空！");
    }

    if (!getPagePv()) {
      throw new Error("pv不能为空！");
    }

    if (!getPageUv()) {
      throw new Error("uv不能为空！");
    }

    return true;
  } else {
    return !!page.settings.pagename &&
      !!selfData.platcode &&
      !!page.settings.productcode &&
      !!getSessionId() &&
      !!getPagePv() &&
      !!getPageUv() &&
      !!selfData.appId &&
      !!selfData.appVersion
  }

}

function setOpenId(cb, that) {
  let hostParams = wx.getStorageSync(STORAGE_KEY.hostParams) || {}
  let tcOpenId = wx.getStorageSync(STORAGE_KEY.openId)
  let openId = tcOpenId || hostParams.openId || ''
  selfData.openid = openId
  baseInfo.oid = openId
  cb && cb();
}

function Page(settings) {
  if (!(this instanceof Page)) return new Page(settings);
  this.init(settings)
}

function EV(settings) {
  if (!(this instanceof EV)) return new EV(settings);
  this.init(settings)
}
// function elEV(settings) {
//   if (!(this instanceof elEV)) return new elEV(settings);
//   elSelfDataDeal();
//   this.init(settings)
// }
function setPageName(tracer) {
  isObject(tracer.settings.pagename) && (tracer.settings.pagename = tracer.settings.pagename["__route__"]);
}

var systemInfo = {}
function getSystemInfo(cb) {
  if (systemInfo.brand) {
    cb && cb(systemInfo)
  } else {
    try {
      systemInfo = wx.getSystemInfoSync()
      cb && cb(res)
    } catch (e) {
      wx.getSystemInfo({
        success: function (res) {
          systemInfo = res
          cb && cb(res)
        }
      })
    }


  }
}

function getwxrefid() {
  let pages = getCurrentPages();
  let wxrefid = wx.getStorageSync(STORAGE_KEY.shipRefId) || '512810788'
  if (pages.length) {
    let currentPage = pages[pages.length - 1]
    currentPage && (wxrefid = (currentPage.options || {}).wxrefid || wxrefid)
  }
  return wxrefid
}

function stay() {
  if (!(this instanceof stay)) return new stay();
  this.init()
}


stay.prototype = {
  constructor: stay,
  init: function () {
    this.startTime = 0;
    this.endTime = 0;
    this.costTime = 0;
  },
  start: function () {
    this.startTime = +new Date();
  },
  end: function () {
    this.endTime = +new Date();
  },
  cost: function () {
    this.end();
    this.costTime = this.endTime - this.startTime;
    return this.costTime;
  }
}


var EVArr = []
var evTimeout = ''
EV.prototype = {
  constructor: EV,
  init: function (settings) {
    this.settings = Object.assign({}, config, settings);
    setPageName(this)
  },
  submit: function () {
    var that = this;
    setLocation();
    if (eventParamsCheck(that)) {
      setOpenId(function () {
        getSystemInfo(function (res) {
          var data = {};
          data.sid = getSessionId();
          data.pc = getPagePv();
          data.sc = getPageUv();
          data.pn = that.settings.pagename;
          data.pdc = that.settings.productcode;
          data.ctg = that.settings.category;
          data.ac = that.settings.action;
          data.lb = that.settings.label;
          data.vl = that.settings.value;
          data.expandfield = that.settings.expandfield;
          // data.wxappScene = getApp().globalData.scene;
          // data.wallet = getApp().globalData.wallet;
          data.refid = getwxrefid();
          data.rpagename = that.settings.rpagename;
          data.pagestate = that.settings.pagestate;
          data.pagedetail = that.settings.pagedetail;
          data.innerRefId = that.settings.innerRefid;
          // data.mvt = encodeURIComponent(JSON.stringify(getApp().globalData.tjObj));
          data.eventid = that.settings.eventid;
          data.cliktime = Date.now();
          data.entertime = that.settings.entertime;
          data.leavetime = that.settings.leavetime;
          data.orgpagename = that.settings.orgpagename;
          if (that.settings.getData) {
            let obj = {
              ...data,
              ...baseInfo
            }
            that.settings.getData(obj)
            return;
          }
          if (that.settings.immediately) {
            setBaseInfo();
            let obj = {
              ...data,
              ...baseInfo
            }

            wx.request({
              url: 'https://wx.17u.cn/trendapi/event',
              method: "POST",
              timeout: 8000,
              header: {
                "Content-Type": "text/plain"
              },
              data: encodeURIComponent(JSON.stringify(obj))
            })
            return false;
          }
          EVArr.push(data)
          if (EVArr.length >= 30) {
            clearTimeout(evTimeout)
            postEV()
          }
          clearTimeout(evTimeout)
          evTimeout = setTimeout(() => {
            postEV()
          }, 5000)
        })
      }, that);
    }
  }
}

function setBaseInfo() {
  if (!baseInfo.brand) {
    baseInfo.brand = systemInfo.brand;
    baseInfo.model = systemInfo.model;
    baseInfo.pixelRatio = systemInfo.pixelRatio;
    baseInfo.screenWidth = systemInfo.screenWidth;
    baseInfo.screenHeight = systemInfo.screenHeight;
    baseInfo.windowWidth = systemInfo.windowWidth;
    baseInfo.windowHeight = systemInfo.windowHeight;
    baseInfo.language = systemInfo.language;
    baseInfo.version = systemInfo.version;
    baseInfo.system = systemInfo.system;
    baseInfo.platform = systemInfo.platform;
    baseInfo.fontSizeSetting = systemInfo.fontSizeSetting;
    baseInfo.SDKVersion = systemInfo.SDKVersion;
  }
  if (!baseInfo.oid) {
    baseInfo.oid = selfData.openid || ''
  }
  if (!baseInfo.uid) {
    baseInfo.uid = wx.getStorageSync(STORAGE_KEY.memberId);
  }
  if (!baseInfo.unionid) {
    baseInfo.unionid = wx.getStorageSync(STORAGE_KEY.unionId);
  }
  if (!baseInfo.ctry) {
    baseInfo.ctry = selfData.country;
    baseInfo.pv = selfData.province;
    baseInfo.ct = selfData.city;
    baseInfo.cty = selfData.county;
  }
}

function postEV() {
  if (EVArr.length > 0) {
    setBaseInfo();
    let len = EVArr.length;
    let newArr = EVArr.splice(0, len);
    while (newArr.length) {
      let postArr = newArr.splice(0, 15);
      let obj = {};
      obj = {
        ...baseInfo,
        _list: postArr
      }
      eventUrl = 'https://wx.17u.cn/wireless/monitor/wx/common/compressevent'
      wx.request({
        priority: 3,
        url: eventUrl,
        method: "POST",
        timeout: 8000,
        data: encodeURIComponent(JSON.stringify(obj))
      })
    }
  }
}
var PageArr = [];
var pageTimeout = ''
Page.prototype = {
  constructor: Page,
  init: function (settings) {
    this.settings = Object.assign({}, config, settings);
    setPagePv(); //设置PV
    setPageName(this);
  },
  submit: function () {
    var that = this;
    if (pageParamsCheck(that)) {
      setLocation();
      setConnection();
      setOpenId(function () {
        getSystemInfo(function (res) {
          var data = {};
          data.pn = that.settings.pagename;
          data.sid = getSessionId();
          data.pc = getPagePv();
          data.sc = getPageUv();
          that.settings.stayTime && (data.stayTime = that.settings.stayTime);
          data.pdc = that.settings.productcode;
          data.orgpagename = that.settings.orgpagename;
          data.rsid = that.settings.resourceid;
          data.innerRefId = that.settings.innerRefid;
          data.expandfield = that.settings.expandfield;
          data.adaid = that.settings.adaid;
          data.serialid = that.settings.serialid;
          data.prepayid = that.settings.prepayid;
          // data.wxappScene = getApp().globalData.scene;
          // data.wallet = getApp().globalData.wallet;
          data.rpagename = that.settings.rpagename;
          data.pagestate = that.settings.pagestate;
          data.pagedetail = that.settings.pagedetail;
          data.locationtime = Date.now();
          // data.mvt = encodeURIComponent(JSON.stringify(getApp().globalData.tjObj));
          data.network = selfData.Connection
          if (that.settings.getData) {
            let obj = {
              ...data,
              ...baseInfo
            }
            that.settings.getData(obj)
            return;
          }
          if (that.settings.immediately) {
            setBaseInfo();
            let obj = {
              ...data,
              ...baseInfo
            }
            wx.request({
              url: 'https://wx.17u.cn/trendapi/pageview',
              method: "POST",
              timeout: 8000,
              header: {
                "Content-Type": "text/plain"
              },
              data: encodeURIComponent(JSON.stringify(obj))
            })
            return false;
          }
          PageArr.push(data)
          if (PageArr.length >= 5) {
            clearTimeout(pageTimeout)
            postPage()
          }
          clearTimeout(pageTimeout)
          pageTimeout = setTimeout(() => {
            postPage()
          }, 5000)
        })
      })
    }
  },
  pageStay: function () {

  }
}
function postPage() {
  if (PageArr.length > 0) {
    setBaseInfo();
    let newArr = PageArr.splice(0, PageArr.length);
    let obj = {};
    obj = {
      ...baseInfo,
      _list: newArr
    }
    pageUrl = 'https://wx.17u.cn/wireless/monitor/wx/common/compresspageview';

    wx.request({
      priority: 3,
      url: pageUrl,
      method: "POST",
      timeout: 8000,
      data: encodeURIComponent(JSON.stringify(obj))
    })
  }
}

// elEV.prototype = {
//   constructor: elEV,
//   init: function (settings) {
//     this.settings = util.extend({}, elconfig, settings, elSelfData);
//   },
//   submit: function () {
//     var that = this;
//     setTimeout(() => {
//       wx.request({
//         url: eleventUrl,
//         method: "GET",
//         timeout: 8000,
//         priority: 3,
//         data: that.settings,
//       })
//     }, 0)

//   }
// }

module.exports = {
  page: Page,
  event: EV,
  stay: stay,
  // elevent: elEV,
  setSessionId: setSessionId,
  postEV: postEV,
  postPage: postPage
};